package com.huangliusong.spring.servlet.controller;


import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.Random;
import java.util.concurrent.*;


/**
 * @author huangliusong
 * @since 2018/10/1
 * {@link RestController}
 */
@RestController
@EnableScheduling
public class HelloWorldController {
    private final BlockingQueue<DeferredResult<String>> queue=new ArrayBlockingQueue<>(5);

    //产生随机数
    private final Random random=new Random();
    @Scheduled(fixedRate = 5000)
    public void process() throws InterruptedException {
        //定时操作
        DeferredResult<String> result=null;
        do {
            result=queue.take();
            //lo
            long timeout=random.nextInt(100);
            //模拟等待事件，PRC或者DB查询
            Thread.sleep(timeout);
            result.setResult("HHOO");
            println("hls:::!!!!!!!：");
        }while (result!=null);


    }



    @GetMapping("/callable-hello-world")
    public Callable<String> callableHelloWorld1(){
        long startTime=System.currentTimeMillis();

        println("he1");
        return ()->{
            long costTime=System.currentTimeMillis()-startTime;

            println("he2"+costTime+" 耗时");
            return "hl";
        };
    }


    @GetMapping("/hello-world")
    public DeferredResult<String> helloWorld(){
        DeferredResult<String> result=new DeferredResult<>(50L);
        //入队操作： queu
        queue.offer(result);
        //result.setResult("nihao hls");

        result.onCompletion(()->{
            System.err.println("执行结束!");
            println("onCompletion");

        });
        result.onTimeout(()->{
            System.err.println("执行超时!");
            println("onTimeout");
        });
        return result;
    }


    private static void println(Object object){
        String threadName=Thread.currentThread().getName();
        System.err.println("线程名称 "+threadName+" "+object);
    }

    @GetMapping("/completionStage-hi")
    public CompletionStage<String> completionStage(){
        final long startTime=System.currentTimeMillis();
        println("CompletionStage");
        return CompletableFuture.supplyAsync(()->{
            long costTime=System.currentTimeMillis();
            println("CompletionStage"+" "+(costTime-startTime));
            return "CompletionStageHello";
        });

    }
}
